<template>
  <div class="center">
    <el-row>
      <el-col :span="16">
        <div class="flex h-10 items-center justify-around">
          <div>督学室名称: {{roomInfo.name}}</div>
          <div>学员数: {{count}}</div>
          <div>创建时间: {{roomInfo.create_time | newDate}}</div>
        </div>
      </el-col>
      <el-col :span="7">
        <div class="float-right">
          <el-button type="primary" @click="dialogVisible=true">开始督学</el-button>
          <el-button icon="el-icon-refresh-right" type="primary" @click="refresh">刷新</el-button>
          <el-button icon="el-icon-arrow-left" type="primary" @click="back">返回</el-button>
        </div>
      </el-col>
    </el-row>
    <div class="flex flex-row flex-wrap">
      <div class="w-36 h-48 m-6 border-dotted border-slate-500 flex flex-col items-center pt-3" v-for="student in studentArr" :key="student.id">
        <div>
          <div class="relative left-[80px] text-xs -top-3">
            <span v-if="student.is_online==1" class="text-lime-600">待学习</span>
            <span v-else-if="student.is_online==2" class="text-lime-600">学习中</span>
            <span v-else class="text-rose-700">离线</span>
          </div>
          <el-image class="w-20 h-20 pb-3" :src="student.avatar" fit="contain"></el-image>
        </div>
        <div class="text-current text-xs leading-5">{{student.account}}</div>
        <div class="text-current text-xs leading-5">{{student.username}}</div>
        <div class="text-current text-xs leading-5">{{student.gradeName}}</div>
      </div>
    </div>
    <el-dialog title="设置课时信息" :visible.sync="dialogVisible" width="40%">
      <el-form :model="roomForm" ref="ruleForm" :rules="rules">
        <el-form-item label="课时时长:" label-width="130px" prop="class_hour">
          <el-time-picker
            is-range
            v-model="roomForm.class_hour"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"
            :default-value="value1"
            value-format="HH:mm:ss">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="课时数量:" label-width="130px" prop="class_count">
          <el-select v-model="roomForm.class_count" placeholder="请选择">
            <el-option
              v-for="item in classCountOption"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学生弹窗确认:" label-width="130px" prop="open_window">
          <el-radio-group v-model="roomForm.open_window">
            <el-radio :label="1">需要</el-radio>
            <el-radio :label="-1">不需要</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="startTeach">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {getClassroom, getStudentByRoomId, startTeaching} from "@/api/teacher";
import mqttHandle from "@/utils/mqttHandler";
var client = null;  //mqtt的实例
export default {
  name: "index",
  data() {
    return {
      roomID: this.$route.query.roomID,
      teacherId: this.$route.query.teacherId,
      count: 0,
      imgSrc: "https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg",
      dialogVisible: false,
      value1: [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 9, 40)],
      roomForm: {
        class_hour: '',
        class_count: '',
        open_window: -1,
      },
      studentArr: [],
      classCountOption: [
        {label: '1', value: 1},
        {label: '1.5', value: 1.5},
        {label: '2', value: 2},
        {label: '2.5', value: 2.5},
        {label: '3', value: 3},
        {label: '3.5', value: 3.5},
        {label: '4', value: 4},
        {label: '4.5', value: 4.5},
        {label: '5', value: 5}],
      rules: {
        class_hour: [{required: true, message: '请选择督学时间', trigger: 'change'}],
        class_count: [{required: true, message: '请设置课时数量', trigger: 'change'}],
        open_window: [{required: true, message: '请选择是否需要平板端弹窗确认', trigger: 'blur'}],
      },
      topicSends: [], //订阅的topic 例如：["Time1", "EngineMain1", "Console1", "Location1"]
      roomInfo: {}
    }
  },
  created(){
    this.$nextTick(() => {
      this.getStudents()
      this.getClassroomControl()
    })
  },
  beforeDestroy() {
    this.disConnect()
  },
  methods: {
    refresh() {
      this.getStudents()
    },
    back() {
      this.$router.back()
    },
    startTeach() {
      let form = JSON.parse(JSON.stringify(this.roomForm))
      form.userId = localStorage.getItem("ID")
      form.teacherId = this.teacherId
      form.roomId = this.roomID
      form.type = 1
      startTeaching(form).then(res => {
        let courseId = res.data.course_id
        //通知房间内所有对象更新督 / 伴学状态
        this.studentArr.forEach((item,index) => {
          let topic = "/control/" + item.id + "/command"
          let now = new Date()
          let payload = {messageType:20, timestamp:now.toJSON(), message:courseId};
          payload = JSON.stringify(payload)
          client.publish(topic, payload, { qos: 0, retain: true }, error => {
            if (error) {
              console.log('Publish error', error)
            }
          })
        })
        this.dialogVisible = false
        this.$router.push({name: 'teaching', query: {courseId: courseId, teacherId: this.teacherId}});
      }).catch(err => {
      })
    },
    getStudents() {
      getStudentByRoomId({
        roomId: this.roomID,
      }).then(res => {
        this.studentArr = res.data
        this.roomInfo =res.otherData
        this.count = this.studentArr.length
        this.setTopic(res.data)
        this.createMqtt()
      }).catch(err => {
        this.studentArr = []
      })
    },
    getClassroomControl() {
      getClassroom({
        roomId: this.roomID
      }).then(res => {
        this.roomForm.class_hour = res.data.class_hour
        this.roomForm.class_count = res.data.class_count
        this.roomForm.open_window = res.data.open_window
      })
    },
    setTopic(data) {
      let that = this
      data.forEach(function (element) {
        let topic = '/control/' + element.id + '/report'
        if (!that.topicSends.includes(topic)) {
          that.topicSends.push(topic)
        }
      })
    },
    /**创建mqtt**/
    createMqtt() {
      var mqtt; //mqtt 处理对象（全局变量）
      //创建链接，接收数据
      mqtt = new mqttHandle(this.topicSends);
      client = mqtt.createConnect();
      client.on("message", (topic, message) => {
        //数据分类
        try {
          let messageData  =  JSON.parse(message)
          let arr = topic.split('/')
          let studentId = arr[2]
          let type = arr[3]
          if (type === 'report') {
            switch (messageData.messageType) {
              case 205: //设备在线状态消息
                this.studentArr.forEach((item, index, arr) => {
                  if(item.id == studentId ) {
                    let temp = this.studentArr[index];
                    temp.is_online = messageData.message
                    this.studentArr.splice(index, 1, temp)
                  }
                })
                break
            }
          }
        } catch (error) {
          console.log("这是error", error)
        }
      });
    },
    //停止订阅mqtt
    disConnect() {
      if (client != null) {
        client.unsubscribe(this.topicSends);
        client = null;
      }
    },
  }
}
</script>

<style scoped>

</style>
